﻿using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastIM
{
    /// <summary>
    /// 消息发布订阅接口
    /// </summary>
    public interface IPubsub
    {
        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="channel">频道</param>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public long Publish(string channel, object message);
        /// <summary>
        /// 订阅频道信息
        /// </summary>
        /// <param name="channels"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public IDisposable Subscribe(string[] channels, Action<string, object> handler);
        /// <summary>
        /// 订阅一个频道
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public IDisposable Subscribe(string channel, Action<string, object> handler);
    }
    /// <summary>
    /// 基于redis的消息发布订阅
    /// </summary>
    public class RedisPubsub : IPubsub
    {
        private RedisClient _redis;
        public RedisPubsub(RedisClient redis)
        {
            _redis = redis;
        }
        public long Publish(string channel, object message)
        {
            return _redis.Publish(channel, message is string ? message.ToString() : JsonConvert.SerializeObject(message));
        }


        public IDisposable Subscribe(string[] channels, Action<string, object> handler)
        {
            return _redis.Subscribe(channels, handler);
        }
        public IDisposable Subscribe(string channel, Action<string, object> handler)
        {
            return _redis.Subscribe(channel, handler);
        }
    }
}
